﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nRoute.Services;
using System.IO.IsolatedStorage;
using System.Configuration;
using nRoute.Components.Composition;
using System.Windows;
using nRoute.Samples.ExtendedMVVM.Properties;
using System.IO;

namespace nRoute.Samples.ExtendedMVVM.Services
{
    [MapService(typeof(ILocalStoreService), InitializationMode = InitializationMode.OnDemand, Lifetime = InstanceLifetime.Singleton)]
    public class LocalStoreService
        : ILocalStoreService
    {
        private const string FILE_FORMAT = "{0}.data";

        public void Save(string key, string value)
        {
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");

            var _store = IsolatedStorageFile.GetUserStoreForAssembly();
            using (var _fileStream = _store.CreateFile(string.Format(FILE_FORMAT, key)))
            {
                using (var _writer = new StreamWriter(_fileStream))
                {
                    _writer.Write(value);
                    _writer.Flush();
                }
            }            
        }

        public string Load(string key)
        {
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");

            var _store = IsolatedStorageFile.GetUserStoreForAssembly();
            if (_store.FileExists(string.Format(FILE_FORMAT, key)))
            {
                using (var _fileStream = _store.OpenFile(string.Format(FILE_FORMAT, key), System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (var _reader = new StreamReader(_fileStream))
                    {
                        return _reader.ReadToEnd();
                    }
                }
            }
            else
            {
                return null;
            }
        }
    }
}
